package org.xnsg.app.controller.utils;

import com.alibaba.fastjson.JSONObject;
import com.eova.common.utils.data.CloneUtil;
import com.eova.common.utils.xx;
import com.eova.engine.DynamicParse;
import com.eova.engine.EovaExp;
import com.eova.model.MetaField;
import com.eova.widget.WidgetManager;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.io.IOException;
import java.util.List;

/**
 * @author zhaopan
 * @date :2017/4/19
 * @Description:控制层工具类
 */
public class ControllerHelper
{
    public static List comboJson(String exp, String ob, String fi, Object[] os)
    {

        MetaField ei = null;
        List list = null;

        try
        {
            if (xx.isEmpty(exp))
            {

                ei = MetaField.dao.getByObjectCodeAndEn(ob, fi);
                exp = ei.getStr("exp");
            }
            //Object[] os = new Object[]{this.getSessionAttr("user")};
            DynamicParse.buildSql(exp, os);
            EovaExp se1 = new EovaExp(exp);
            String sql = se1.sql;
            list = (List) CloneUtil.clone(Db.use(se1.ds).findByCache("serviceCache", sql, sql));
        } catch (IOException var8)
        {
            var8.printStackTrace();
        } catch (ClassNotFoundException var9)
        {
            var9.printStackTrace();
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        Record re = new Record();
        if (ei == null || !ei.getBoolean("is_multiple").booleanValue())
        {
            re.set("id", "");
            re.set("cn", "");
            list.add(0, re);
        }

        return list;
    }

    public static String findCnByEn(String code, String en, String value, Object[] os)
    {
        MetaField ei = MetaField.dao.getByObjectCodeAndEn(code, en);
        String exp = ei.getStr("exp");
        exp = DynamicParse.buildSql(exp, os);
        EovaExp se = new EovaExp(exp);
        String ds = se.ds;
        StringBuilder sb = new StringBuilder();
        String sql;
        if (!xx.isEmpty(value))
        {
            sb.append(se.pk);
            sb.append(" in(");
            String[] var12;
            int json = (var12 = value.split(",")).length;

            for (int txts = 0; txts < json; ++txts)
            {
                sql = var12[txts];
                sb.append(xx.format(sql)).append(",");
            }

            sb.deleteCharAt(sb.length() - 1);
            sb.append(")");
        }

        System.out.println(sb.toString());
        sql = WidgetManager.addWhere(se, sb.toString());
        List var13 = Db.use(ds).find(sql);
        if (xx.isEmpty(var13))
        {
            return value;
        } else
        {
            JSONObject var14 = new JSONObject();
            var14.put("text_field", se.cn);
            var14.put("data", JsonKit.toJson(var13));
            return var14.toJSONString();
        }
    }
}
